package com.itheima.service.mongo.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class VideoServiceImpl implements VideoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PageBeanVo findRecommendVideoByPage(Long userId, Integer pageNum, Integer pageSize) {
        int starIndex = (pageNum - 1) * pageSize;
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("date")))
                .skip(starIndex).limit(pageSize);
        List<RecommendVideo> recommendVideoList = mongoTemplate.find(query, RecommendVideo.class);
        long count = mongoTemplate.count(query, RecommendVideo.class);
        ArrayList<Video> videoArrayList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(recommendVideoList)) {
            for (RecommendVideo recommendVideo : recommendVideoList) {
                ObjectId videoId = recommendVideo.getVideoId();
                Video video = mongoTemplate.findById(videoId, Video.class);
                videoArrayList.add(video);
            }
        }
        return new PageBeanVo(pageNum, pageSize, count, videoArrayList);
    }

    @Autowired
    private RedisIdService redisIdService;

    @Override
    public void publishVideo(Video video) {
        //设置大数据id
        Long vid = redisIdService.getNextId(ConstantUtil.VIDEO_ID);
        video.setVid(vid);
        mongoTemplate.save(video);

        //推荐给自己 不然看不到
        RecommendVideo recommendVideo = new RecommendVideo();

        recommendVideo.setVideoId(video.getId());
        recommendVideo.setDate(System.currentTimeMillis());
        recommendVideo.setVid(vid);
        recommendVideo.setScore(99.0);
        recommendVideo.setUserId(video.getUserId());

        mongoTemplate.save(recommendVideo);
    }

    @Override
    public PageBeanVo findVideoByPage(Long userId, Integer pageNum, Integer pageSize) {
        int starIndex = (pageNum - 1) * pageSize;

        Query query = new Query(Criteria.where("userId").is(userId)).skip(starIndex).limit(pageSize).with(Sort.by(Sort.Order.asc("created")));

        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);

        return new PageBeanVo(pageNum,pageSize,count,videoList);
    }

}
